package com.example.fresh_market.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.Toast;

import com.example.fresh_market.constants.StrConstant;
import com.example.fresh_market.databinding.ActivityLoginBinding;
import com.example.fresh_market.request.ApiResponse;
import com.example.fresh_market.request.AuthRespVO;
import com.example.fresh_market.utils.HttpUtil;
import com.example.fresh_market.utils.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.Map;


public class LoginActivity extends AppCompatActivity {

    private final Context mContext = this;
    private ActivityLoginBinding binding;
    private CheckBox remember_me;
    private CheckBox auto_login;
    private SharedPreferences preferences;

    public void handlePermission() {
        // 检查是否开启 Manifest.permission.xxx
        // (xxx 为权限，根据自己需求添加）
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "Permission has been allowed", Toast.LENGTH_SHORT).show();
        } else {
            // 请求权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        handlePermission();
        binding.buttonLog.setOnClickListener(v -> login());
        binding.buttonSign.setOnClickListener(v -> {
            startActivity(new Intent(mContext, RegisterActivity.class));
        });
        binding.buttonToAdmin.setOnClickListener(v -> {
            startActivity(new Intent(mContext, AdminLoginActivity.class));
        });
        binding.buttonToSudo.setOnClickListener(v -> {
            startActivity(new Intent(mContext, SudoLoginActivity.class));
        });
        handleCheckBox();
    }

    private void handleCheckBox() {
        preferences = getSharedPreferences(StrConstant.CONFIG, MODE_PRIVATE);
        remember_me = binding.rememberMe;
        auto_login = binding.autoLogin;
        boolean remember = preferences.getBoolean(StrConstant.REMEMBER, false);
        boolean autologin = preferences.getBoolean(StrConstant.AUTO_LOGIN, false);
        remember_me.setChecked(remember);
        auto_login.setChecked(autologin);
        auto_login.setOnClickListener(view -> {
            if (auto_login.isChecked()) {
                remember_me.setChecked(true);
            } else {
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean(StrConstant.AUTO_LOGIN, false);
                editor.apply();
            }

        });
        remember_me.setOnClickListener(view -> {
            if (!remember_me.isChecked()) {
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean(StrConstant.REMEMBER, false);
                editor.apply();
            }
        });

        if (remember) {
            String username = preferences.getString(StrConstant.USERNAME, "");
            String password = preferences.getString(StrConstant.PASSWORD, "");
            binding.etUsername.setText(username);
            binding.etPassword.setText(password);
        }
        if (autologin) {
            String username = preferences.getString(StrConstant.USERNAME, "");
            String password = preferences.getString(StrConstant.PASSWORD, "");
            binding.etUsername.setText(username);
            binding.etPassword.setText(password);
            login();
        }
    }

    public void login() {
        String username = binding.etUsername.getText().toString();
        String password = binding.etPassword.getText().toString();
        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(mContext, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
        } else {
            Map<String, String> params = new HashMap<>();
            // 在这里添加表单字段
            params.put("username", username);
            params.put("password", password);
            HttpUtil.post(mContext, "/user/login", params, response -> {
                Log.d("", response);
                ToastUtil.showToast(mContext, "登录成功");
                Gson gson = new Gson();
                ApiResponse<AuthRespVO> apiResponse = gson.fromJson(response, new TypeToken<ApiResponse<AuthRespVO>>() {
                }.getType());
                SharedPreferences.Editor editor = preferences.edit();
                if (remember_me.isChecked()) {
                    editor.putString(StrConstant.USERNAME, username);
                    editor.putString(StrConstant.PASSWORD, password);

                }
                editor.putBoolean(StrConstant.AUTO_LOGIN, auto_login.isChecked());
                editor.putBoolean(StrConstant.REMEMBER, remember_me.isChecked());
                editor.putString(StrConstant.TOKEN, apiResponse.getData().getToken());
                editor.apply();
                startActivity(new Intent(mContext, MainActivity.class));
            });
        }
    }
}